﻿// template uri resolver
// allows DTD declaration and xml document conformance
using System;
using System.Collections.Generic;
using System.Xml;

namespace Landscape
{
    internal class TemplateXmlUrlResolver : XmlUrlResolver
    {
        private Dictionary<int, string> IncludeDirs;

        public XmlReaderSettings Settings
        {
            get;
            set;
        }

        private System.Net.ICredentials _Credentials;
        public override System.Net.ICredentials Credentials
        {
            set { _Credentials = value; }
        }

        public TemplateXmlUrlResolver(Dictionary<int, string> _IncludeDirs)
        {
            IncludeDirs = _IncludeDirs;
            Settings = new XmlReaderSettings();
            Settings.DtdProcessing = DtdProcessing.Parse;
            Settings.ConformanceLevel = ConformanceLevel.Document;

            _Credentials = System.Net.CredentialCache.DefaultCredentials;
        }

        public override Uri ResolveUri(Uri baseUri, string relativeUri)
        {
            string extension = System.IO.Path.GetExtension(relativeUri).ToLower();

            if (extension == ".xslt!")
            {
                string filename = System.IO.Path.GetFileName(relativeUri);
                filename = filename.Substring(0, filename.Length - 1);
                string includePath = Globals.LookupFile(filename, IncludeDirs);

                if (!string.IsNullOrEmpty(includePath)) {
                    return new Uri(includePath);
                }
            }

            return base.ResolveUri(baseUri, relativeUri);
        }

        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) {
            XmlReader reader = XmlReader.Create(absoluteUri.AbsoluteUri, Settings);
            return reader;

        }
    }
}
